<?
User::$current = new User();

class User
{
	var 	$groups 	= 	array(),$privilege 	= 	array(),$data=array('id'=>'0','email'=>'');
	static 	$current	=	false,	$info		=	false,	$permits	=	'',		$user_lock = 0;
	
	function User()
	{
		if(!isset($_SESSION['user_id']))
		{
			$_SESSION['user_id']=0;
		}
		
		if($_SESSION['user_id'])
		{
			$user	=	User::getUser((int)$_SESSION['user_id']);			
			if($user && (!USER_ACTIVE_ON || (USER_ACTIVE_ON && $user['user_activated']==0)))
			{
				$this->groups = User::get_groups($user['gids']);
				
				if(!self::checkLock4Ever(true))
				{
					if(!isset($this->groups[1]) && !isset($this->groups[2]) && $_SESSION['user_id']!=4 && (trim($user['email'])=='' || $user['block_time'] > TIME_NOW || $user['block_time']==-1))
					{
						self::$user_lock = 1;
							
						if($user['block_time']==-1)//Khoá vĩnh viễn
						{
							$user_lock = DB::select('user_lock','user_id='.$user['user_id'].' AND type IN(1,3) ORDER BY id DESC');
							
							if($user_lock)
							{
								if($user_lock['type']==3)//Khoá cookie
								{
									self::lock4Ever(true,$user['id']);
								}
							}
							
							self::LogOut();
						}
						else
						{
							$this->data = $user;//$_SESSION['user_lock'] = 1;
							User::$info = $user;//$_SESSION['user_lock'] = 1;
							
							$_SESSION['user_email'] = $user['email'];
						}
					}
					else
					{
						$this->data=$user;
						User::$info=$user;
						
						$_SESSION['user_email']	=	$user['email'];
					}
				}
			}
			else
			{
				self::LogOut();
			}
		}
	}
	
	static function checkLock4Ever($kick_out=false)//Hàm kiểm tra khoá người dùng vĩnh viễn từ cookie
	{
		if(isset(User::$current->groups[1])||isset(User::$current->groups[2])||$_SESSION['user_id']==4){
			if(isset($_SESSION['lock_4ever']))$_SESSION['lock_4ever']=0;
			if(isset($_COOKIE['lock_4ever'])) ECLib::my_setcookie('lock_4ever',0,TIME_NOW-1);
			return false;
		}
		else{
			if(isset($_COOKIE['lock_4ever']) || (isset($_SESSION['lock_4ever'])&&$_SESSION['lock_4ever']) ){
				ECLib::my_setcookie('lock_4ever',1);
				
				if($kick_out){
					self::lock4Ever(true);
				}
				else{
					$_SESSION['lock_4ever']=1;
				}
				return true;	
			}
			return false;
		}
	}
	
	static function lock4Ever($kick_out=false,$user_id=false){
		ECLib::my_setcookie('lock_4ever',1);
		User::LogOut();
		if($kick_out && $user_id){
			DB::delete(_SESS_TABLE,'id='.$user_id,__LINE__.__FILE__);
		}
		else{
			$_SESSION['lock_4ever']=1;
		}
	}
	
	static function getUser($user_id, $delcache=false)
	{
		$user=array();

		if($user_id)
		{
			if(MEMCACHE_ON)
			{
				if($delcache){//Xoá cache
					if(MEMCACHE_ON){
						ECMemcache::do_remove("user:$user_id");
					}
					return true;
				}
				else
				{
					if(MEMCACHE_ON){
						$user = ECMemcache::do_get("user:$user_id");
					}
					
					if(!$user){
						$sql 	= "SELECT * FROM ".TABLE_PREFIX."user WHERE id=".(int)$user_id." LIMIT 1";
						$user 	= mysql_fetch_assoc(DB::query($sql));
						
						$user['is_block'] = ($user['block_time']>TIME_NOW || $user['block_time']==-1)?true:false;
						
						if(MEMCACHE_ON && $user){
							ECMemcache::do_put("user:$user_id" , $user);
						}
					}
				}
			}
			else{//cache file
				$subDir='user/'.floor($user_id/1000);
				
				//$user 	= ECCache::cache("SELECT * FROM ".TABLE_PREFIX."user WHERE id=".(int)$user_id." LIMIT 0,1",__LINE__.__FILE__,2592000,0,'',$subDir,$delcache);
                $sql 	= "SELECT * FROM ".TABLE_PREFIX."user WHERE id=".(int)$user_id." LIMIT 1";
                $user 	= mysql_fetch_assoc(DB::query($sql));
				if($user&&!$delcache){
					$user[0]['is_block'] = ($user[0]['block_time']>TIME_NOW || $user[0]['block_time']==-1)?true:false;
					return $user;
				}
			}
		}
		return $user;
	}
	
	static function getByEmail($user_email,$update_cache=false,$delcache=false){
		$user=array();
		
		if($user_email)
		{
			$sql = "SELECT id AS id FROM " . TABLE_PREFIX . "user WHERE email='$user_email' LIMIT 1";

			if(CACHE_ON)
			{
				$subDir='user/user_by_email/';

				$user_temp = ECCache::cache($sql,__LINE__.__FILE__,2592000,$update_cache,'',$subDir,$delcache);
				
				if(!$user_temp || ($user_temp && !is_array($user_temp))){
					$user_temp = ECCache::cache($sql,__LINE__.__FILE__,2592000,1,'',$subDir,$delcache);
				}

				if($user_temp)
				{
					foreach($user_temp as $user_tmp)
					{
						//return self::getUser($user_temp[0]['id'],$delcache);

						return self::getUser($user_tmp['id'],$delcache);
					}
				}
				else//Xóa cache nếu ko tồn tại
				{
					ECCache::cache($sql,__LINE__.__FILE__,2592000,0,'',$subDir,1);
				}
			}
			else{
				if($user_email){
					$subDir='user/user_by_email/';
					
					$user = ECCache::cache($sql,__LINE__.__FILE__,1,$update_cache,'',$subDir,$delcache);
				}			
				if($user&&!$delcache)
				{
					foreach($user as $user_tmp)
					{
						$user_tmp['is_block'] = ($user_tmp['block_time']>TIME_NOW || $user_tmp['block_time']==-1)?true:false;

						return $user_tmp;
					}
					//$user[0]['is_block'] = ($user[0]['block_time']>TIME_NOW || $user[0]['block_time']==-1)?true:false;
					//return $user[0];
				}	
			}
		}
		return $user;		
	}
	
	static function LogIn($user_or_id)
	{
		if(is_array($user_or_id) && isset($user_or_id['id']))
			$user_id=(int)$user_or_id['id'];
		else 
			$user_id = $user_or_id;
			
		$_SESSION['user_id']	= $user_id;
		
		if($user_id)
		{
			DB::query("UPDATE ".TABLE_PREFIX."user SET last_ip='".ECLib::ip()."' WHERE id=".$user_id, __LINE__.__FILE__);
			
			$user	=	User::getUser($user_id);
			
			if($user)
			{
				User::$current->data	=	$user;
				User::$info				=	$user;
				
				$_SESSION['user_email']	=	$user['email'];
			}
		}
	}
	
	static function LogOut()
	{
		if((int)$_SESSION['user_id'])
		{
			DB::query("UPDATE ".TABLE_PREFIX."user SET last_ip='".ECLib::ip()."' WHERE id=".(int)$_SESSION['user_id'],__LINE__.__FILE__);
		}
		
		$_SESSION['user_id']	=0;
		$_SESSION['user_email']  ='';
		
		if(isset($_SESSION['user_lock'])){
			$_SESSION['user_lock']=null;
			unset($_SESSION['user_lock']);
		}
		
		//Remove remember password cookies:
		if(isset($_COOKIE['ecore_id']) || isset($_COOKIE['password'])){
			ECLib::my_setcookie('ecore_id',"",TIME_NOW-3600);
			ECLib::my_setcookie('password',"",TIME_NOW-3600);
		}
	}
	
	static function is_block(){
		return self::$user_lock;//(isset($_SESSION['user_lock']) && $_SESSION['user_lock']);
	}
	
	static function is_login(){
		return (isset($_SESSION['user_id']) && $_SESSION['user_id']!=0);
	}
	
	static function check_cookie_login($user_id,$password)
	{	
		$user_data=DB::fetch('SELECT id, email, password, block_time, gids FROM '.TABLE_PREFIX.'user WHERE id='.(int)$user_id,false,false,__LINE__.__FILE__);
		
		if($user_data && isset($user_data['user_pass_md5']) && $user_data['user_pass_md5'] == $password)
		{
			if($user_data['block_time'] > TIME_NOW)//Nếu User bị khóa chưa hết hạn!
			{
				self::LogOut();
			}
			else//TuanNK sửa check quyền đăng nhập, nếu thuộc nhóm quản trị ==>> không cho đăng nhập tự động
			{
				$in_group_admin=false;
				
				if($user_data['gids'] && $user_data['gids']!='0')
				{
					//$in_group_admin=(preg_match("/(".$user_data['gids'].")/is","2") || preg_match("/(".$user_data['gids'].")/is","1"));
					$in_group_admin=(preg_match("/(".$user_data['gids'].")/is","3") || preg_match("/(".$user_data['gids'].")/is","2") || preg_match("/(".$user_data['gids'].")/is","1") || preg_match("/(".$user_data['gids'].")/is","9"));
				}
				
				if(!$in_group_admin)
				{
					User::Login($user_data);
					
					Url::redirect_url(Url::build_all());
				}
				else
				{
					ECLib::my_setcookie('ecore_id',"",TIME_NOW-3600);
					ECLib::my_setcookie('password',"",TIME_NOW-3600);
				}
			}
		}
		else{
			self::LogOut();
		}
	}
	
	static function encode_password($password){
		return md5($password);
	}
	
	static function is_root(){//power admin
		return self::is_login()?(isset(self::$current->groups['9'])||$_SESSION['user_id'] == 22):false;
	}
	
	static function is_admin(){
		return self::is_login()?(isset(self::$current->groups['1'])||self::is_root()||$_SESSION['user_id']==4):false;
	}

	static function is_mod(){
		return self::is_login()?(isset(self::$current->groups['2'])||self::is_admin()):false;
	}
	
	static function is_admin_team()
	{
		return self::is_login() ? (bool) self::$current->groups:false;
	}

    static function is_admin_hotel(){
        return self::is_login()?(isset(self::$current->groups['10'])):false;
    }

	static function check_admin($gids)
	{
		if($gids && $gids!='0')
		{
			if(preg_match("/([\D])9([\D])/i","|$gids|")) return 9;//Root
			elseif(preg_match("/([\D])1([\D])/i","|$gids|")) return 1;//Admin
			elseif(preg_match("/([\D])2([\D])/i","|$gids|")) return 2;//Mod
			elseif(preg_match("/([\D])3([\D])/i","|$gids|")) return 3;//Mod for category
			elseif(preg_match("/([\D])4([\D])/i","|$gids|")) return 4;//Low Mod
		}
		
		return 0;
	}
	
	static function check_higher_permis($gids_current,$gids)
	{
		$gids_current = self::check_admin($gids_current);
		$gids 		  = self::check_admin($gids);
		
		if($gids==9){//is root
			if($gids_current==1 || $gids_current==2 || $gids_current==3){
				return false;
			}
		}
		elseif($gids==1){//is admin
			if($gids_current==2 || $gids_current==3){
				return false;
			}
		}
		elseif($gids==2){//is mod
			if($gids_current==3){//is mod cat
				return false;
			}
		}
		
		return true;		
	}

	static function get_groups($gids)
	{
		self::get_system_groups();

		$groups=array();
		
		if($gids)
		{
			$gids_arr=explode('|',$gids);
			
			if($gids_arr)
			{
				$all_groups = self::get_system_groups();
				
				foreach ($gids_arr as $gid)
				{
					if(isset($all_groups[$gid]))
					{
						$groups[$gid] = $all_groups[$gid];
					}
				}
			}
		}
		
	    return $groups;
	}
	
	static function get_system_groups($del_cache = 0)
	{
		$groups = ECCache::cache("SELECT * FROM user_groups",__LINE__.__FILE__,36000,0,'','',$del_cache);
		
		if($groups)
		{
			$groups = CGlobal::$group + $groups;
		}

	    return $groups;
	}
	
	static function id()
	{
		return isset($_SESSION['user_id'])?(int)$_SESSION['user_id']:0;
	}
	
	static function user_email()
	{
		if(isset($_SESSION['user_id']))
		{
			if(isset($_SESSION['user_email'])&&$_SESSION['user_email'])
			{
				return $_SESSION['user_email'];
			}
			elseif(isset(User::$info['email']))
			{
				return User::$info['email'];
			}
		}
		
		return '';
	}
	
	static function user_name()
	{
		if(isset($_SESSION['user_id']))
		{
			if(isset(User::$info['user_name']))
			{
				return User::$info['user_name'];
			}
		}
		
		return '';
	}
	
	static function have_permit($pids, $redirect_page = false){
		if(User::is_login())
		{
			if(is_array($pids))
			{
				foreach ($pids as $pemiss)
				{
					if(User::have_permit($pemiss))
					return true;
				}
				
				return false;
			}
			
			if(User::is_admin())
			{
				return true;
			}
			
			if(User::$current->groups)//Nếu đã phân nhóm
			{
				self::get_permits();
				
				//return User::$permits !='' && User::$permits!='0' && preg_match("/([\D])".$pids."([\D])/is",'|'.User::$permits.'|');

				return User::$permits !='' && User::$permits!='0' && (stripos('|' . User::$permits . '|' , '|' . $pids.'|') !== false);
			}
		}
		
		if($redirect_page)
		{
			Url::redirect($redirect_page);
		}
		else
		{
			return false;
		}
	}
	
	static function get_permits($del_cache=false,$user_id=false)
	{
		static $get_permits=0;
		
		if($del_cache && $user_id>0 && $user_id != User::id())
		{
			$user = User::getUser($user_id);
			
			if($user && $user['gids']){
				//$gids	=	str_replace('|',',',$user['gids']);
				$gids	=	$user['gids'];
			}
			else{
				return false;
			}
		}
		elseif($del_cache || !$get_permits)
		{
			$user_id = User::id();
			//$gids	 = str_replace('|',',',self::$info['gids']);
			$gids	 = self::$info['gids'];
		}
		
		if($del_cache || !$get_permits)
		{	
			$permits = ECCache::cache("SELECT type,ref_id,pids FROM user_permit WHERE (ref_id IN(".$gids.") AND type=0) OR (ref_id=".$user_id." AND type=1)",__LINE__.__FILE__,36000,0,'','',$del_cache);
		}
		
		if(!$get_permits && !$del_cache)
		{	
			if($permits)
			{
				foreach ($permits as $permit)
				{
					if($permit['pids'])
						User::$permits.=(User::$permits?'|':'').$permit['pids'];
					
				}
			}
			
			$get_permits=1;
		}
	}
	
	static function check_get_user()
	{	 
		if(Url::get('user_id')){
			if(User::is_login() && User::id()==Url::get('user_id')){
				CGlobal::$user_profile = User::$info;
			}
			else
				CGlobal::$user_profile = User::getUser(Url::get('user_id'));			
		}
		
		if(!CGlobal::$user_profile && Url::get('email')){
			if(User::is_login() && User::user_email()==Url::get('email')){
				CGlobal::$user_profile = User::$info;
			}
			else{
				CGlobal::$user_profile = User::getByEmail(Url::get('email'));
			}
		}
		
		if(!CGlobal::$user_profile && User::is_login() && in_array(ECore::$page['name'],array('personal','message','cart','gold_history'))){
			CGlobal::$user_profile = User::$info;
		}
		
		if(!CGlobal::$user_profile){
			Url::access_denied();				
		}		
	}
	
	static function delete_user($user_id){
		if($user_id){
			
			$items = array();
			$str_ids = "";
						
			DB::delete("user","id=$user_id");	
					
			if(MEMCACHE_ON){
				ECMemcache::do_remove("user:$user_id");
			}
		}
	}
	
	static function log_action($arrData)
	{
		if(!is_array($arrData) || !$arrData)
		{
			return false;
		}
		else 
		{
			DB::insert("user_log_action",$arrData);
			return true;
		}
	}
}
?>